/* eslint-disable prettier/prettier */
// src/articles/articles.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Knowledge } from './schemas/knowledge.schemas';
import { CreateKnowledgeDto } from './dto/create-knowledge.dto';

@Injectable()
export class KnowledgeService {
  constructor(
    @InjectModel(Knowledge.name) private knowledgeModel: Model<Knowledge>,
  ) { }

  create(CreateKnowledgeDto: CreateKnowledgeDto) {
    return this.knowledgeModel.create(CreateKnowledgeDto);
  }

  async findAll(): Promise<Knowledge[]> {
    return this.knowledgeModel.find().exec();
  }

  async findOne(id: string) {
    const data = await this.knowledgeModel.findOne({ _id: id }).exec();
    if (id.trim() === '') {
      return {
        code: 200,
        msg: "入参不合法！"
      }
    } else {
      return {
        code: 200,
        msg: "查询成功！",
        data
      }
    }
  }

  // 分页查询
  async findSearch(pageNum: number, likeFlag: number) {
    if (pageNum >= 1 && 0 <= likeFlag && likeFlag <= 4) {
      const data = await this.knowledgeModel
        .find({ likeFlag })
        .skip((pageNum - 1) * 4) // 跳过前 (pageNum - 1) * pageSize 条数据
        .limit(4) // 限制每页的数据数量
        .exec();
      if (data.length === 0) {
        return {
          code: 200,
          msg: "暂无更多数据！"
        }
      } else {
        return {
          code: 200,
          msg: "搜索成功!",
          data
        }
      }
    } else {
      return {
        code: 200,
        msg: "入参不合法！"
      }
    }
  }

  async update(id: string, updateArticleDto: CreateKnowledgeDto): Promise<Knowledge> {
    return this.knowledgeModel.findOneAndUpdate(
      { _id: id },
      updateArticleDto,
      { new: true },
    ).exec();
  }

  async remove(id: string): Promise<Knowledge> {
    return this.knowledgeModel.findOneAndDelete({ _id: id }).exec();
  }
}